import requests
import csv
from bs4 import BeautifulSoup


# 将爬取的网页输出CSV

def clawing():
    url = 'https://down.ali213.net/pcgame/'
    resp = requests.get(url)
    soup = BeautifulSoup(resp.content.decode('utf-8'), 'lxml')
    game_list = soup.find_all(class_='famous-li')

    res_list = []
    for game in game_list:
        game_name = game.find(class_='game-name').string
        game_down = game.find(class_='game-down')['href']
        game_down_size = game.find(class_='game-down').string
        row_dict = {'name': game_name, 'down': game_down, 'size': game_down_size}
        res_list.append(row_dict)
    return res_list

# 写入csv文件
def insertCsv():
    game_list = clawing()
    with open('e://download/data.csv', 'w', encoding='gbk') as file:
        fieldnames = ['name', 'down', 'size']
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        for game in game_list:
            writer.writerow(game)

# 读取文件
def readCsv():
    with open('e://download/data.csv','r',encoding='gbk') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
readCsv()
